<?php
/**
 * Description
 *
 * PHP version 7
 *
 * @category Custom
 * @package  Custom
 * @author   ryu <mo5467@126.com>
 * @date     2020-04-30 00:09:44
 * @lastTime 2020-05-02 00:24:17
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     none
 */
namespace Design\Other\Repository;

class PostRepository
{

    private $persistence;


    public function __construct(Persistence $persistence)
    {
        $this->persistence = $persistence;

    }//end __construct()


    public function generateId() : PostId
    {
        return PostId::fromInt($this->persistence->generateId());

    }//end generateId()


    public function findById(PostId $id) : Post
    {
        try {
            $arrayData = $this->persistence->retrieve($id->toInt());
        } catch (\OutOfBoundsException $e) {
            throw new \OutOfBoundsException(sprintf('Post with id %d not found', $id->toInt()), 0, $e);
        }

        return Post::fromState($arrayData);

    }//end findById()


    public function save(Post $post)
    {
        $this->persistence->persist(
            [
                'id'     => $post->getId()->toInt(),
                'status' => $post->getStatus()->toString(),
                'title'  => $post->getTitle(),
                'text'   => $post->getText(),
            ]
        );

    }//end save()

    public function remove(Post $post)
    {
        $this->persistence->delete($post->getId()->toInt());
    }


}//end class
